package com.avecsys.quotemanager.mbeans.supplier;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icefaces.ace.component.fileentry.FileEntry;
import org.icefaces.ace.component.fileentry.FileEntryEvent;
import org.icefaces.ace.component.fileentry.FileEntryResults;
import org.icefaces.ace.component.fileentry.FileEntryResults.FileInfo;
import org.icefaces.ace.event.SelectEvent;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.BuyerMasterPojo;
import com.avecsys.quotemanager.pojos.BuyerUsersPojo;
import com.avecsys.quotemanager.pojos.QuoteTransactionEventsPojo;
import com.avecsys.quotemanager.pojos.QuoteTransactionPojo;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;
import com.avecsys.quotemanager.service.buyer.BuyerMasterService;
import com.avecsys.quotemanager.service.supplier.QuoteTransactionService;
import com.avecsys.quotemanager.ui.components.LookUpDialog;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;
import com.avecsys.quotemanager.vo.SupplierVO;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlInputTextarea;

/**
 * @author Sam Sundar K
 */
public class SendQuoteToBuyerMBean extends BaseMBean implements Serializable
{
	private final Log log = LogFactory.getLog(SendQuoteToBuyerMBean.class);

	private QuoteTransactionService quoteTransactionService;

	private BuyerMasterService buyerMasterService;

	private QuoteTransactionPojo quoteTransactionsPojo = new QuoteTransactionPojo();

	private QuoteTransactionEventsPojo quoteTransactionEventsPojo = new QuoteTransactionEventsPojo();

	private String sendEmailNotificationTo;

	private List<BuyerMasterPojo> lookUpListBuyerMasterPojo = new ArrayList<BuyerMasterPojo>();

	private List<BuyerUsersPojo> lookUpListbuyerUsersPojo = new ArrayList<BuyerUsersPojo>();

	private LookUpDialog<BuyerMasterPojo> lookUpDialogBuyerMaster = new LookUpDialog<BuyerMasterPojo>(
			"lookUpDialogBuyerMasterID", new ArrayList<BuyerMasterPojo>());

	private LookUpDialog<BuyerUsersPojo> lookUpDialogBuyerUsersPojo = new LookUpDialog<BuyerUsersPojo>(
			"lookUpDialogBuyerUserPojoID", new ArrayList<BuyerUsersPojo>());

	private HtmlInputText widgetQuoteName;

	private HtmlInputText widgetBuyerCompany;

	private HtmlInputText widgetSendEmailNotificationTo;

	private HtmlInputTextarea widgetSellerComments;

	private HtmlInputText widgetQuoteValue;

	public String actionCancel()
	{
		return "cancel";
	}

	public void actionClear(ActionEvent actionEvent)
	{
		clearScreen();
	}

	/**
	 * Look Up Action to list all buyers for the logged in supplier
	 * 
	 * @param actionEvent
	 */
	public void actionLookUpBuyer(ActionEvent actionEvent)
	{
		try
		{
			UserMasterPojo userMasterPojo = getSignedInUser();
			for (SupplierUsersPojo supplierUsersPojo : userMasterPojo.getSupplierUsersPojo())
			{
				List<BuyerMasterPojo> buyerMasterPojoList = buyerMasterService.getAllBuyers(supplierUsersPojo.getSupplierMasterPojo());
				getLookUpDialogBuyerMaster().setDataList(buyerMasterPojoList);
				getLookUpDialogBuyerMaster().showDialog();
			}
		}
		catch (BusinessException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	/**
	 * Look Up Action to list all buyer users for the selected buyer
	 * 
	 * @param actionEvent
	 */
	public void actionLookUpBuyerUserEmail(ActionEvent actionEvent)
	{
		try
		{
			if (getQuoteTransactionsPojo().getBuyerMasterPojo() != null
					&& getQuoteTransactionsPojo().getBuyerMasterPojo().isPersisted())
			{
				List<BuyerUsersPojo> buyerMasterPojoList = buyerMasterService.getAllUsers(getQuoteTransactionsPojo().getBuyerMasterPojo());
				getLookUpDialogBuyerUsersPojo().setDataList(buyerMasterPojoList);
				getLookUpDialogBuyerUsersPojo().showDialog();
			}
			else
			{
				FacesMessage message = new FacesMessage();
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				message.setSummary(MessageBoardUtil.getValue(
						FacesContext.getCurrentInstance(),
							ApplicationConstants.RESOURCE_BUNDLE_SUPPLIER,
							ApplicationConstants.VALIDATOR_ERROR_BUYER_SELECTION_REQUIRED,
							null));
				FacesContext.getCurrentInstance().addMessage(getWidgetBuyerCompany().getId(), message);
			}
		}
		catch (BusinessException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	/**
	 * LookUp Action to list all Buyer Users for a Buyer whoe's email is verified
	 * 
	 * @param actionEvent
	 */
	public void actionLookUpBuyerUsers(ActionEvent actionEvent)
	{

	}

	public void actionQuoteAttachmentListener(FileEntryEvent fileEntryEvent)
	{
		FileEntry fileEntry = (FileEntry) fileEntryEvent.getComponent();
		FileEntryResults fileEntryResults = fileEntry.getResults();
		List<FileInfo> fileInfoList = fileEntryResults.getFiles();
		for (FileInfo fileInfo : fileInfoList)
		{
			if (fileInfo.isSaved())
			{
				FacesContext facesContext = FacesContext.getCurrentInstance();
				facesContext.getExternalContext()
						.getSessionMap()
						.put(ApplicationConstants.QUOTE_TRANSACTION_ATTACHEMNT_FILE_INFO, fileInfo);
			}
			else
			{

			}
		}
	}

	/**
	 * Action Method to Send a Quote to a Buyer
	 * 
	 * @return
	 */
	public String actionSendQuoteToBuyer()
	{
		try
		{
			log.info("Started Saving Quote Transaction Information into database");
			// Step1: Update user modification information
			updateUserInformation(quoteTransactionsPojo, null);
			updateUserInformation(quoteTransactionEventsPojo, quoteTransactionsPojo.getModifiedDttm());
			// Step2: Update Logged in user Supplier to Quote
			UserMasterPojo userMasterPojo = getSignedInUser();
			for (SupplierUsersPojo supplierUsersPojo : userMasterPojo.getSupplierUsersPojo())
			{
				quoteTransactionsPojo.setSupplierMasterPojo(supplierUsersPojo.getSupplierMasterPojo());
			}
			// Step2: Save Supplier Quote Template Master Information
			// Prepare Value Object
			SupplierVO supplierVO = new SupplierVO();
			FileInfo quoteAttachmentFileInfo = (FileInfo) FacesContext.getCurrentInstance()
					.getExternalContext()
					.getSessionMap()
					.get(ApplicationConstants.QUOTE_TRANSACTION_ATTACHEMNT_FILE_INFO);
			FacesContext.getCurrentInstance()
					.getExternalContext()
					.getSessionMap()
					.remove(ApplicationConstants.QUOTE_TRANSACTION_ATTACHEMNT_FILE_INFO);
			supplierVO.setQuoteAttachmentFileInfo(quoteAttachmentFileInfo);
			supplierVO.setQuoteTransactionsPojo(quoteTransactionsPojo);
			supplierVO.setQuoteTransactionEventsPojo(quoteTransactionEventsPojo);
			TransactionStatus transactionStatus = quoteTransactionService.saveQuoteTransaction(supplierVO);
			if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.SAVE_SUCESS.ordinal())
			{
				MessageBoardUtil.publishMessage(
						ApplicationConstants.RESOURCE_BUNDLE_SUPPLIER,
							BaseException.SEVERITY_INFO,
							"messageBoardId",
							ApplicationConstants.QUOTE_SENT_TO_BUYER_SUCCESSFULL,
							new Object[]
							{
									quoteTransactionsPojo.getQuoteName(),
									quoteTransactionsPojo.getBuyerMasterPojo()
											.getCompanyMasterPojo()
											.getCompanyName() });
			}
			log.info("Completed saving Quote Transaction Information into database sucessfully");
			clearScreen();
		}
		catch (BaseException e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		catch (Exception e)
		{
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openSentQuoteAllListScreen";
	}

	public void clearScreen()
	{
		setQuoteTransactionsPojo(new QuoteTransactionPojo());
		setSendEmailNotificationTo(null);
		getWidgetQuoteName().setSubmittedValue(null);
		getWidgetQuoteName().setValue(null);
		getWidgetBuyerCompany().setSubmittedValue(null);
		getWidgetBuyerCompany().setValue(null);
		getWidgetSendEmailNotificationTo().setSubmittedValue(null);
		getWidgetSendEmailNotificationTo().setValue(null);
		getWidgetSellerComments().setSubmittedValue(null);
		getWidgetSellerComments().setValue(null);
		getWidgetQuoteValue().setSubmittedValue(0);
		getWidgetQuoteValue().setValue(0);
		FacesContext.getCurrentInstance()
				.getExternalContext()
				.getSessionMap()
				.remove(ApplicationConstants.QUOTE_TRANSACTION_ATTACHEMNT_FILE_INFO);
	}

	/**
	 * @return the buyerMasterService
	 */
	public BuyerMasterService getBuyerMasterService()
	{
		return buyerMasterService;
	}

	/**
	 * @return the lookUpDialogBuyerMaster
	 */
	public LookUpDialog<BuyerMasterPojo> getLookUpDialogBuyerMaster()
	{
		return lookUpDialogBuyerMaster;
	}

	/**
	 * @return the lookUpDialogBuyerUsersPojo
	 */
	public LookUpDialog<BuyerUsersPojo> getLookUpDialogBuyerUsersPojo()
	{
		return lookUpDialogBuyerUsersPojo;
	}

	/**
	 * @return the lookUpListBuyerMasterPojo
	 */
	public List<BuyerMasterPojo> getLookUpListBuyerMasterPojo()
	{
		return lookUpListBuyerMasterPojo;
	}

	/**
	 * @return the lookUpListbuyerUsersPojo
	 */
	public List<BuyerUsersPojo> getLookUpListbuyerUsersPojo()
	{
		return lookUpListbuyerUsersPojo;
	}

	/**
	 * @return the quoteTransactionEventsPojo
	 */
	public QuoteTransactionEventsPojo getQuoteTransactionEventsPojo()
	{
		return quoteTransactionEventsPojo;
	}

	/**
	 * @return the quoteTransactionService
	 */
	public QuoteTransactionService getQuoteTransactionService()
	{
		return quoteTransactionService;
	}

	/**
	 * @return the quoteTransactionsPojo
	 */
	public QuoteTransactionPojo getQuoteTransactionsPojo()
	{
		return quoteTransactionsPojo;
	}

	/**
	 * @return the sendEmailNotificationTo
	 */
	public String getSendEmailNotificationTo()
	{
		return sendEmailNotificationTo;
	}

	/**
	 * @return the widgetBuyerCompany
	 */
	public HtmlInputText getWidgetBuyerCompany()
	{
		return widgetBuyerCompany;
	}

	/**
	 * @return the widgetQuoteName
	 */
	public HtmlInputText getWidgetQuoteName()
	{
		return widgetQuoteName;
	}

	/**
	 * @return the widgetQuoteValue
	 */
	public HtmlInputText getWidgetQuoteValue()
	{
		return widgetQuoteValue;
	}

	/**
	 * @return the widgetSellerComments
	 */
	public HtmlInputTextarea getWidgetSellerComments()
	{
		return widgetSellerComments;
	}

	/**
	 * @return the widgetSendEmailNotificationTo
	 */
	public HtmlInputText getWidgetSendEmailNotificationTo()
	{
		return widgetSendEmailNotificationTo;
	}

	public void lookUpActionSelectBuyer(SelectEvent selectEvent)
	{
		BuyerMasterPojo buyerMasterPojo = (BuyerMasterPojo) selectEvent.getObject();
		getQuoteTransactionsPojo().setBuyerMasterPojo(buyerMasterPojo);
		getWidgetBuyerCompany().setValue(buyerMasterPojo.getCompanyMasterPojo().getCompanyName());
		getWidgetBuyerCompany().setSubmittedValue(
				buyerMasterPojo.getCompanyMasterPojo().getCompanyName());
		getLookUpDialogBuyerMaster().hideDialog();
	}

	public void lookUpActionSelectBuyerUser(SelectEvent selectEvent)
	{
		BuyerUsersPojo buyerUsersPojo = (BuyerUsersPojo) selectEvent.getObject();
		setSendEmailNotificationTo(buyerUsersPojo.getUserMasterPojo().getEmail());
		getWidgetSendEmailNotificationTo().setValue(buyerUsersPojo.getUserMasterPojo().getEmail());
		getWidgetSendEmailNotificationTo().setSubmittedValue(
				buyerUsersPojo.getUserMasterPojo().getEmail());
		getLookUpDialogBuyerUsersPojo().hideDialog();
	}

	/**
	 * @param buyerMasterService the buyerMasterService to set
	 */
	public void setBuyerMasterService(BuyerMasterService buyerMasterService)
	{
		this.buyerMasterService = buyerMasterService;
	}

	/**
	 * @param lookUpDialogBuyerMaster the lookUpDialogBuyerMaster to set
	 */
	public void setLookUpDialogBuyerMaster(LookUpDialog<BuyerMasterPojo> lookUpDialogBuyerMaster)
	{
		this.lookUpDialogBuyerMaster = lookUpDialogBuyerMaster;
	}

	/**
	 * @param lookUpDialogBuyerUsersPojo the lookUpDialogBuyerUsersPojo to set
	 */
	public void setLookUpDialogBuyerUsersPojo(LookUpDialog<BuyerUsersPojo> lookUpDialogBuyerUsersPojo)
	{
		this.lookUpDialogBuyerUsersPojo = lookUpDialogBuyerUsersPojo;
	}

	/**
	 * @param lookUpListBuyerMasterPojo the lookUpListBuyerMasterPojo to set
	 */
	public void setLookUpListBuyerMasterPojo(List<BuyerMasterPojo> lookUpListBuyerMasterPojo)
	{
		this.lookUpListBuyerMasterPojo = lookUpListBuyerMasterPojo;
	}

	/**
	 * @param lookUpListbuyerUsersPojo the lookUpListbuyerUsersPojo to set
	 */
	public void setLookUpListbuyerUsersPojo(List<BuyerUsersPojo> lookUpListbuyerUsersPojo)
	{
		this.lookUpListbuyerUsersPojo = lookUpListbuyerUsersPojo;
	}

	/**
	 * @param quoteTransactionEventsPojo the quoteTransactionEventsPojo to set
	 */
	public void setQuoteTransactionEventsPojo(QuoteTransactionEventsPojo quoteTransactionEventsPojo)
	{
		this.quoteTransactionEventsPojo = quoteTransactionEventsPojo;
	}

	/**
	 * @param quoteTransactionService the quoteTransactionService to set
	 */
	public void setQuoteTransactionService(QuoteTransactionService quoteTransactionService)
	{
		this.quoteTransactionService = quoteTransactionService;
	}

	/**
	 * @param quoteTransactionsPojo the quoteTransactionsPojo to set
	 */
	public void setQuoteTransactionsPojo(QuoteTransactionPojo quoteTransactionsPojo)
	{
		this.quoteTransactionsPojo = quoteTransactionsPojo;
	}

	/**
	 * @param sendEmailNotificationTo the sendEmailNotificationTo to set
	 */
	public void setSendEmailNotificationTo(String sendEmailNotificationTo)
	{
		this.sendEmailNotificationTo = sendEmailNotificationTo;
	}

	/**
	 * @param widgetBuyerCompany the widgetBuyerCompany to set
	 */
	public void setWidgetBuyerCompany(HtmlInputText widgetBuyerCompany)
	{
		this.widgetBuyerCompany = widgetBuyerCompany;
	}

	/**
	 * @param widgetQuoteName the widgetQuoteName to set
	 */
	public void setWidgetQuoteName(HtmlInputText widgetQuoteName)
	{
		this.widgetQuoteName = widgetQuoteName;
	}

	/**
	 * @param widgetQuoteValue the widgetQuoteValue to set
	 */
	public void setWidgetQuoteValue(HtmlInputText widgetQuoteValue)
	{
		this.widgetQuoteValue = widgetQuoteValue;
	}

	/**
	 * @param widgetSellerComments the widgetSellerComments to set
	 */
	public void setWidgetSellerComments(HtmlInputTextarea widgetSellerComments)
	{
		this.widgetSellerComments = widgetSellerComments;
	}

	/**
	 * @param widgetSendEmailNotificationTo the widgetSendEmailNotificationTo to set
	 */
	public void setWidgetSendEmailNotificationTo(HtmlInputText widgetSendEmailNotificationTo)
	{
		this.widgetSendEmailNotificationTo = widgetSendEmailNotificationTo;
	}
}
